import React, { useState, useRef, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { Toast } from 'antd-mobile';
import axios from 'axios';
import { saveUserInfo, getUserInfo } from '../utils/auth';
import styles from './Renlianlogin.module.css';
import  {http,host,port} from '../utils/host'
const Renlianlogin: React.FC = () => {
    const navigate = useNavigate();
    const videoRef = useRef<HTMLVideoElement>(null);
    const canvasRef = useRef<HTMLCanvasElement>(null);
    const [isLoading, setIsLoading] = useState(false);
    const [isRecording, setIsRecording] = useState(false);
    const [stream, setStream] = useState<MediaStream | null>(null);
    const [errorMsg, setErrorMsg] = useState('');
    const [currentStep, setCurrentStep] = useState(0);
    const [hasBoundFace, setHasBoundFace] = useState(false);

    // 检查用户是否已绑定人脸
    useEffect(() => {
        const realName = localStorage.getItem('realName');
        if (realName) {
            setHasBoundFace(true);
        } else {
            setHasBoundFace(false);
        }
    }, []);

    // 开始摄像头
    const startCamera = async () => {
        try {
            const mediaStream = await navigator.mediaDevices.getUserMedia({
                video: {
                    width: { ideal: 640 },
                    height: { ideal: 480 },
                    facingMode: 'user'
                }
            });
            
            if (videoRef.current) {
                videoRef.current.srcObject = mediaStream;
                setStream(mediaStream);
            }
        } catch (error) {
            console.error('摄像头启动失败:', error);
            Toast.show({
                content: '摄像头启动失败，请检查权限设置',
                position: 'center',
            });
        }
    };

    // 停止摄像头
    const stopCamera = () => {
        if (stream) {
            stream.getTracks().forEach(track => track.stop());
            setStream(null);
        }
        if (videoRef.current) {
            videoRef.current.srcObject = null;
        }
    };

    // 开始人脸识别
    const startFaceRecognition = async () => {
        if (!hasBoundFace) {
            Toast.show({
                content: '请先绑定人脸',
                position: 'center',
            });
            return;
        }

        if (!stream) {
            Toast.show({
                content: '请先启动摄像头',
                position: 'center',
            });
            return;
        }

        setIsLoading(true);
        setCurrentStep(1);
        setErrorMsg('');

        try {
            // 等待视频加载
            await new Promise(resolve => setTimeout(resolve, 1000));

            if (!videoRef.current || !canvasRef.current) {
                throw new Error('视频或画布元素未找到');
            }

            const video = videoRef.current;
            const canvas = canvasRef.current;
            const ctx = canvas.getContext('2d');

            if (!ctx) {
                throw new Error('无法获取画布上下文');
            }

            // 设置画布尺寸
            canvas.width = video.videoWidth;
            canvas.height = video.videoHeight;

            // 绘制视频帧到画布
            ctx.drawImage(video, 0, 0, canvas.width, canvas.height);

            // 获取图像数据
            const imageData = canvas.toDataURL('image/jpeg', 0.8);
            const base64 = imageData.split(',')[1];

            console.log('开始人脸识别...');
            console.log('图像已捕获，大小:', base64.length);

            setCurrentStep(2);

            // 发送到后端进行人脸识别
            const response = await axios.post(`${http}${host}${port}/faceLogin`, {
                base64: base64,
                realName: localStorage.getItem('realName')  // 发送当前用户的实名信息
            });

            if (response.data.code === 0) {
                setCurrentStep(3);
                
                // 获取原有的用户信息
                const existingUserInfo = getUserInfo();
                if (existingUserInfo) {
                    // 使用原有的用户信息，保持与其他登录方式一致
                    saveUserInfo(existingUserInfo);
                    
                    Toast.show({
                        content: '人脸识别成功，身份验证通过',
                        position: 'center',
                    });

                    // 停止摄像头
                    stopCamera();

                    // 登录成功后跳转
                    setTimeout(() => {
                        navigate('/layout/home');
                    }, 1000);
                } else {
                    Toast.show({
                        content: '用户信息获取失败，请重新登录',
                        position: 'center',
                    });
                }
            } else {
                // 身份验证失败
                setErrorMsg(response.data.msg || '人脸识别失败，请确保是本人操作');
                setCurrentStep(0);
            }

        } catch (error: any) {
            console.error('人脸识别错误:', error);
            
            let errorMessage = '人脸识别失败，请重试';
            if (error.code === 'ERR_NETWORK') {
                errorMessage = '网络连接失败，请检查后端服务是否启动';
            } else if (error.response?.data?.msg) {
                errorMessage = error.response.data.msg;
            } else if (error.response?.status === 404) {
                errorMessage = '人脸识别接口不存在，请检查后端服务';
            } else if (error.response?.status === 500) {
                errorMessage = '服务器内部错误';
            }
            
            setErrorMsg(errorMessage);
            setCurrentStep(0);
        } finally {
            setIsLoading(false);
        }
    };

    // 组件卸载时停止摄像头
    useEffect(() => {
        return () => {
            stopCamera();
        };
    }, []);

    const stepMessages = [
        '准备开始人脸识别',
        '正在捕获图像...',
        '正在验证身份...',
        '身份验证成功！'
    ];

    return (
        <div className={styles['face-login-container']}>
            {/* 背景装饰元素 */}
            <div className={styles['background-decoration']} />
            <div className={styles['background-decoration-2']} />

            {/* 主要内容区域 */}
            <div className={styles['main-content']}>
                {/* 返回按钮 */}
                <div className={styles['back-button']} onClick={() => navigate('/login')}>
                    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                        <path d="M19 12H5"/>
                        <path d="M12 19l-7-7 7-7"/>
                    </svg>
                </div>

                {/* 标题区域 */}
                <div className={styles['title-section']}>
                    <h1 className={styles['welcome-title']}>人脸登录</h1>
                    <p className={styles['subtitle']}>快速安全的人脸识别登录</p>
                </div>

                {/* 摄像头区域 */}
                <div className={styles['camera-section']}>
                    {!hasBoundFace ? (
                        <div className={styles['bind-face-tip']}>
                            <div className={styles['bind-face-icon']}>👤</div>
                            <div className={styles['bind-face-text']}>
                                <h3>请先绑定人脸</h3>
                                <p>您还没有绑定人脸信息，无法使用人脸登录</p>
                            </div>
                            <button 
                                className={styles['bind-face-button']}
                                onClick={() => navigate('/myprivacy')}
                            >
                                去绑定人脸
                            </button>
                        </div>
                    ) : (
                        <>
                            <div className={styles['video-container']}>
                                <video
                                    ref={videoRef}
                                    autoPlay
                                    playsInline
                                    muted
                                    className={styles['video']}
                                />
                                <canvas ref={canvasRef} style={{ display: 'none' }} />
                            </div>

                            {/* 状态提示 */}
                            {isLoading && (
                                <div className={styles['status-overlay']}>
                                    <div className={styles['status-content']}>
                                        <div className={styles['loading-spinner']}></div>
                                        <div className={styles['status-text']}>
                                            {stepMessages[currentStep]}
                                        </div>
                                    </div>
                                </div>
                            )}

                            {/* 错误信息 */}
                            {errorMsg && (
                                <div className={styles['error-message']}>
                                    {errorMsg}
                                </div>
                            )}

                            {/* 操作按钮 */}
                            <div className={styles['action-buttons']}>
                                {!stream ? (
                                    <button
                                        className={styles['start-button']}
                                        onClick={startCamera}
                                    >
                                        启动摄像头
                                    </button>
                                ) : (
                                    <button
                                        className={styles['recognize-button']}
                                        onClick={startFaceRecognition}
                                        disabled={isLoading}
                                    >
                                        {isLoading ? '验证中...' : '开始身份验证'}
                                    </button>
                                )}
                            </div>
                        </>
                    )}
                </div>

                {/* 分割线 */}
                <div className={styles['divider']}>
                    <span>其他登录方式</span>
                </div>

                {/* 其他登录方式 */}
                <div className={styles['other-login-methods']}>
                    <button
                        className={styles['other-login-button']}
                        onClick={() => navigate('/login')}
                    >
                        📱 手机号登录
                    </button>
                    <button
                        className={styles['other-login-button']}
                        onClick={() => navigate('/emaillogin')}
                    >
                        📧 邮箱登录
                    </button>
                </div>
            </div>
        </div>
    );
};

export default Renlianlogin;